﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Xml;

namespace VLog
{
    /// <summary>
    /// SQL数据库 日志 
    /// </summary>
    public class SqlVLog : VLogBase
    {
        public SqlVLog()
        {
            this.Path = LogCommons.GetPath(PathType.DataBase);
        }

        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        protected override bool Write(VLogEntity entity)
        {

            using (SqlConnection sqlconn = new SqlConnection(this.Path))
            {
                using (SqlCommand sqlcomm = new SqlCommand(
                    "INSERT INTO [Web_ExceptionLog]([ExceptionID],[FullInfo],[Senders],[OccurTime],[HttpMethod],[Level]) VALUES (@ExceptionID,@FullInfo,@Senders,@OccurTime,@HttpMethod,@Level);"
                    , sqlconn))
                {
                    SqlParameter parameter = new SqlParameter("@ExceptionID", SqlDbType.VarChar, 36);
                    parameter.Value = entity.ExceptionID;
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@FullInfo", SqlDbType.NText);
                    parameter.Value = string.Format(@"<p>{0}</p>"
                                         , entity.FullInfo
                                       );
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@OccurTime", SqlDbType.DateTime, 4);
                    parameter.Value = DateTime.Now;
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@Senders", SqlDbType.VarChar, 2000);
                    parameter.Value = base.RequestReffer;
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@HttpMethod", SqlDbType.VarChar, 50);
                    parameter.Value = base.HttpMethod;
                    sqlcomm.Parameters.Add(parameter);

                    parameter = new SqlParameter("@Level", SqlDbType.Int);
                    parameter.Value = entity.Level;
                    sqlcomm.Parameters.Add(parameter);

                    sqlconn.Open();
                    sqlcomm.ExecuteNonQuery();
                    sqlconn.Close();
                }
            }
            OnAddVLog(entity); //触发写日志事件，外部订阅这个事件的对象将被执行
            return true;
        }


    }
}
